#!/usr/bin/python
#coding=utf-8

import Cookie
import utils.log_utils as log
import os

class Request:

    def __init__(self, environ):
        self.method = environ['REQUEST_METHOD']
        self.uri = environ['REQUEST_URI']
        self.query_string = environ['QUERY_STRING']
        self.path_info = environ['PATH_INFO']
        self.server_protocol = environ['SERVER_PROTOCOL']
        self.server_name = environ['SERVER_NAME']
        self.server_port = environ['SERVER_PORT']
        self.cookie_string = environ.get('HTTP_COOKIE')
        self.args = {}
        self.__set_args(environ)

    def __set_args(self, environ):
        if self.method == 'GET':
            if self.query_string:
                log.debug('get method, query_string=' + self.query_string)
                self.process(self.query_string)
        elif self.method == 'POST':
            query_string = environ['wsgi.input'].read()
            if query_string:
                log.debug('post method, query_string=' + query_string)
                self.process(query_string)
        else:
            raise Exception('not support method')

    def process(self, raw_string):
        preprocess = raw_string.strip().replace(' ', '')
        args_list = preprocess.split('&')
        for arg in args_list:
            key, value = tuple(arg.split('='))
            self.args[key] = value

    def cookie(self):
        if not hasattr(self, 'cookies'):
            self.cookies = Cookie.SimpleCookie() 
            if self.cookie_string:
                self.cookies.load(self.cookie_string)
        return self.cookies



